package bookez.view.bean.validator;

import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import bookez.model.businessobject.BusType;
import bookez.model.exception.BusinessLogicLayerException;
import bookez.view.bean.BaseBean;
import bookez.view.bean.BusTypeBean;
import bookez.view.util.ProcessMessage;

@ManagedBean
@ApplicationScoped
@FacesValidator(value = "busTypeNameValidator")
public class BusTypeNameValidator extends BaseBean implements Validator {

    private FacesContext context;
    private UIComponent ui;
    private String name;
    
    @Override
    public void validate(FacesContext context, UIComponent ui, Object value)
            throws ValidatorException {
        
        setUpFields(context, ui, value);
        
        if (name.isEmpty()) {
            processIfValueIsEmtpy();
        } else {
            if(busTypeExisting()) {
                processIfDuplicatedBusType();
            }
        }
    }
    
    private void setUpFields(FacesContext context, UIComponent ui, Object value) {
        this.context = context;
        this.ui = ui;
        this.name = (String) value;
    }
    
    private void processIfValueIsEmtpy() {
        markGuiInvalid();
        sendMessageErrorToGui(BusTypeBean.NAME_REQUIRED, null);
    }
    
    private void markGuiInvalid() {
        ((UIInput) ui).setValid(false);
    }
    
    private void sendMessageErrorToGui(String message, Object[] params) {
        ProcessMessage.processError(ui.getClientId(context),
                message, params);
    }
    
    private void processIfDuplicatedBusType() {
        markGuiInvalid();
        sendMessageErrorToGui(BusTypeBean.NAME_EXISTS, new Object[] {name});
    }
    
    
    private boolean busTypeExisting() {
        try {
            BusType result =
                getServiceLocator().getBusTypeService().getBusTypeByName(name);
            
            if (result != null) {
                return false;
            }
            
            return true;
        } catch (BusinessLogicLayerException e) {
            throw new RuntimeException();
        }
    }

    private static final long serialVersionUID = 3272697781803970701L;
}// end class BusTypeNameValidator
